import { onMounted, onUnmounted } from 'vue'

export function useAnimation() {
  // 视差效果
  const handleParallax = (e) => {
    const parallaxElements = document.querySelectorAll('.parallax-text')
    parallaxElements.forEach(el => {
      const speed = el.getAttribute('data-speed')
      const x = (window.innerWidth - e.pageX * speed) / 100
      const y = (window.innerHeight - e.pageY * speed) / 100
      el.style.transform = `translateX(${x}px) translateY(${y}px)`
    })
  }

  // 滚动动画
  const handleScrollAnimation = () => {
    const elements = document.querySelectorAll('.fade-in-section')
    elements.forEach(el => {
      const rect = el.getBoundingClientRect()
      const isVisible = (rect.top <= window.innerHeight * 0.75)
      if (isVisible) {
        el.classList.add('is-visible')
      }
    })
  }

  // 观察元素进入视口
  const observeIntersection = (el, callback) => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            callback()
            observer.unobserve(el)
          }
        })
      },
      { threshold: 0.1 }
    )
    observer.observe(el)
  }

  onMounted(() => {
    window.addEventListener('mousemove', handleParallax)
    window.addEventListener('scroll', handleScrollAnimation)
    handleScrollAnimation()
  })

  onUnmounted(() => {
    window.removeEventListener('mousemove', handleParallax)
    window.removeEventListener('scroll', handleScrollAnimation)
  })

  return {
    handleParallax,
    handleScrollAnimation,
    observeIntersection
  }
}
